#!/usr/bin/env python
# coding=utf-8

import requests
# from bs4 import BeautifulSoup
import json
import re
import os
# 'ascii' codec can't encode characters
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from BaiduMusicUtils import MusicDownload

class BaiduMusicDownload(object):

    def __init__(self):
        self.__BASE_URL = r'http://music.baidu.com/artist/{author_id}'
        self.__SONG_DATA_URL = r'http://music.baidu.com/data/music/fmlink?songIds='
        self.__SONG_SEARCH_URL = None
        self.__SONG_REAL_DATA = None
        self.__SONG_REAL_URL = None 

        # Song info
        self.__SONG_ID = None
        self.__SONG_NAME = None
        self.__SONG_AUTHOR = None
        self.__SONG_FORMAT = None
        self.__SONG_ALBUM = None

    def get_author_song_id_list(self, author_id):
        self.__SONG_SEARCH_URL = self.__BASE_URL.format(author_id=author_id)

        req = requests.get(self.__SONG_SEARCH_URL)
        song = req.content

        song_id_list = re.findall(r'data-ids="([^"]+)"', str(song))
        #try:
        #    self.__SONG_AUTHOR = re.findall(r'"artistname", "([^"]+)"', song)[0]
        #except IndexError:
        #    self.__SONG_AUTHOR = re.findall(r'<h1>([^"]+)</h1>', song)[0]

        if len(song_id_list) == 0:
            return False
        
        self.__SONG_ID = song_id_list[0].split(',')
        return song_id_list

    def get_real_song_data(self, song_id):
        data_url = self.__SONG_DATA_URL+str(song_id)
        req = requests.get(data_url)

        song_data = json.loads(str(req.content))['data']
        if song_data != '':
            songList = song_data['songList'][0]
    #        self.__SONG_NAME = songList['songName']
            self.__SONG_AUTHOR = str(songList['artistName'].replace(' ', ''))
    #        self.__SONG_FORMAT = songList['format']
    #        self.__SONG_ALBUM = songList['albumName']
    #        self.__SONG_REAL_URL = songList['songLink']
    #    
    #    self.__SONG_REAL_DATA = song_data
    #    return self.__SONG_REAL_DATA
    #
            
    def download_song(self, author_id):
        # 
        self.get_author_song_id_list(author_id)
        self.get_real_song_data(self.__SONG_ID[0])

        if not os.path.exists('artist_'+self.__SONG_AUTHOR):
            os.mkdir('artist_'+self.__SONG_AUTHOR)
        os.chdir('artist_'+self.__SONG_AUTHOR)

        Music = MusicDownload()


        song_id_list = self.__SONG_ID
        
        print "总共%d首" % len(song_id_list)
        i = 1
        while song_id_list:
            print i,'.',
            Music.download_song(song_id_list.pop())
            i += 1

        os.chdir('..')

if __name__ == '__main__':
    import sys
    
    if len(sys.argv) == 1:
        print "Usage:"
        print "\t{filename} Artist".format(filename=sys.argv[0])
        print "\t{filename} Artist1 Artist2 ...".format(filename=sys.argv[0])
        exit(False)

    download = BaiduMusicDownload()
    for song in sys.argv:
        if song == sys.argv[0]:
            continue
        download.download_song(song)
